import os

from flask_cors import CORS
from flask import Flask, request, has_request_context
from applications.common.utils.http import get_real_ip
from applications.config import *
from applications.api import init_bps
from applications.config import Config

from flasgger import Swagger
import applications.common.utils.memory_control


def req_config(app):
    @app.before_request
    def intercept_request():
        if has_request_context():
            request.environ['REMOTE_ADDR'] = get_real_ip()


def create_app():
    app = Flask(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

    CORS(app)  # 全局启用跨域支持

    # 初始化flask
    app.config.from_object(Config)

    req_config(app)

    # 注册 swagger
    Swagger(app, config=swagger_config, template=swagger_template)

    # 注册蓝图
    init_bps(app)

    return app
